export function debounce<T extends (...args: unknown[]) => void>(fn: T, delay: number = 500): (...args: Parameters<T>) => void {
  let timer: ReturnType<typeof setTimeout> | null = null

  return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
    if (timer !== null) {
      clearTimeout(timer)
    }

    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

export function throttle<T extends (...args: unknown[]) => void>(fn: T, delay: number = 500): (...args: Parameters<T>) => void {
  let lastCall = 0
  let timeoutId: ReturnType<typeof setTimeout> | null = null

  return function (...args: Parameters<T>) {
    const now = Date.now()
    if (lastCall + delay <= now) {
      if (timeoutId) {
        clearTimeout(timeoutId)
        timeoutId = null
      }
      lastCall = now
      fn(...args)
    }
    else if (!timeoutId) {
      timeoutId = setTimeout(() => {
        lastCall = Date.now()
        timeoutId = null
        fn(...args)
      }, delay - (now - lastCall))
    }
  }
}

export function convertToChinaNum(num: number): string {
  const arr1: string[] = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const arr2: string[] = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿'] // 可继续追加更高位转换值

  if (isNaN(num) || num === null || num === undefined) {
    return '零'
  }
  if (num === 0) {
    return '零'
  }

  const english: string[] = num.toString().split('')
  let result: string = ''
  let zeroFlag: boolean = false

  for (let i = 0; i < english.length; i++) {
    const des_i: number = english.length - 1 - i // 倒序排列设值
    const arr1_index: number = parseInt(english[des_i])

    if (arr1_index === 0) {
      zeroFlag = true
    }
    else {
      if (zeroFlag) {
        result = arr1[0] + result
        zeroFlag = false
      }
      result = arr1[arr1_index] + arr2[i] + result
    }
  }

  // 将【零千、零百】换成【零】 【十零】换成【十】
  result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十')
  // 合并中间多个零为一个零
  result = result.replace(/零+/g, '零')
  // 将【零亿】换成【亿】【零万】换成【万】
  result = result.replace(/零亿/g, '亿').replace(/零万/g, '万')
  // 将【亿万】换成【亿】
  result = result.replace(/亿万/g, '亿')
  // 移除末尾的零
  result = result.replace(/零+$/, '')
  // 将【零一十】换成【零十】
  // result = result.replace(/零一十/g, '零十'); // 貌似正规读法是零一十
  // 将【一十】换成【十】
  result = result.replace(/^一十/g, '十')

  return result
}

export function isMobile(): boolean {
  return /Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

export function toTwoDecimalPlaces(num: number): number {
  return parseFloat(num.toFixed(2))
}
